from socket import *
import time
import _thread


# 创建socket
tcp_client_socket = socket(AF_INET, SOCK_STREAM)

# 目的信息
server_ip = input("\n请输入服务器ip:")
# server_port = int(input("请输入服务器port:"))
server_port = 7788
# 链接服务器
tcp_client_socket.connect((server_ip, server_port))


# 延迟循环监听数据取回（线程类）
def timerecv(threadName, delay):
    a = 1
    print('\n启动监听线程', threadName, '\n')
    while a == 1:
        recvData = tcp_client_socket.recv(1024)
        if recvData.decode('gbk') == "" or recvData.decode('gbk') == " ":
            time.sleep(0.1)
        else:
            print('\n返回:', recvData.decode('gbk'), '\n')
            time.sleep(0.1)


try:
    _thread.start_new_thread(timerecv, ('Thread1', 1,))
    print("提示: 启动循环监听", '\n')
except:
    print("Error: 无法启动线程", '\n')

time.sleep(1)
# 提示用户输入数据
send_data = input('\n要发送的数据[\"Q!\"-退出|\"H!\"-帮助 ]：')
while send_data != "Q!":
    tcp_client_socket.send(send_data.encode("gbk"))
    send_data = input('\n要发送的数据[\"Q!\"-退出|\"H!\"-帮助 ]：')
else:
    # 关闭套接字
    tcp_client_socket.close()


